<template>
  <div class="drawer-box">
    <el-drawer v-model="showGroupManage" :close-on-click-modal="false" @close="handleCancel">
      <!--    start header-->
      <template #header>
        <div class="drawer-header">
          <title-view title="管理分组" />
        </div>
      </template>
      <!--    end header-->
      <!--    start drawer-content-->
      <div class="drawer-content">
        <!--        start left-content-->
        <div class="left-content" v-loading="isLoadingGroupList">
          <div class="group-information">
            <div v-if="groupList.length" class="group-list">
              <VueDraggableNext
                id="drag-field-container"
                v-model="groupList"
                chosenClass="drag-chosen-field-class"
                :animation="500"
                :forceFallback="true"
                :capture="true"
                handle=".drag-field-handle"
                @start="handleTypeDragStart"
                @end="handleTypeDragEnd"
              >
                <div
                  class="group-item"
                  v-for="(item, index) in groupList"
                  :key="item.groupId"
                  @click.stop="clickGroupItem(item, index)"
                  :class="{ 'group-item--active': currentClickIndex === index || item.isEdit }"
                  :style="{ display: item.groupName === '全部' ? 'none' : 'flex' }"
                >
                  <div class="group-item__title" v-if="!item.isEdit">{{ item.groupName }}</div>
                  <div class="group-item__title" v-else><el-input v-model="item.groupName" style="width: 150px"  maxlength="30" /></div>
                  <div class="group-item__action" v-if="!item.isEdit">
                    <svg-icon iconClass="edit" @click.stop="handelEditGroup(item, index)" size="18" style="margin-right: 5px" />
                    <svg-icon iconClass="del" @click.stop="handelDeleteGroup(item, index)" size="18" style="margin-right: 5px" />
                    <svg-icon class="drag-field-handle" iconClass="sort" size="18" />
                  </div>
                  <div class="group-item__edit" v-else>
                    <svg-icon iconClass="del" size="18" style="margin-right: 5px" @click.stop="handelDeleteGroup(item, index)" />
                    <svg-icon iconClass="complete" @click.stop="saveGroup(item, index)" size="18" />
                  </div>
                </div>
              </VueDraggableNext>
            </div>
            <div v-else><el-empty /></div>
          </div>
          <div class="group-button">
            <el-button block type="primary" :icon="Plus" @click="handelAddGroup">新建分组</el-button>
          </div>
        </div>
        <!--        end left-content-->
        <!--        start right-content-->
        <div class="right-content" v-loading="isLoadingGroupDetail">
          <div class="right-head">
            <CustomerTabs :tab-list="groupTabs" v-model="currentTabIndex" />
            <div class="copy-group">
              <el-dropdown placement="bottom" trigger="click">
                <div class="copy-btn">
                  <el-icon size="14px" color="#007DFF" style="margin-right: 5px"><CopyDocument /></el-icon>
                  复制其他分组
                </div>
                <template #dropdown>
                  <el-dropdown-menu :teleported="false">
                    <el-dropdown-item
                      v-for="(item, index) in filterGroupList"
                      :key="`${item.groupId}-${index}`"
                      @click="copyGroup(item)"
                    >
                      <div class="dropdown-item">
                        <div class="dropdown-item__text">
                          <ellipsis-view :row="1" is-hover-tip :content="item.groupName" />
                        </div>
                        <el-icon size="14px" color="#007DFF" style="margin-right: 5px"><CopyDocument /></el-icon>
                      </div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <div class="setting-content">
            <template v-if="groupId">
              <list-setting v-if="currentTabIndex === 0" v-model="groupListConfig" ref="listSetting" />
              <group-rules v-if="currentTabIndex === 1" v-model="groupRulesConfig" ref="groupRules" />
            </template>
            <el-empty v-else />
          </div>
          <div class="button-action">
            <el-button color="#F2F3F5" @click="handleCancel">取消</el-button>
            <el-button color="#007DFF" @click="handleConfirm" :disabled="!groupId">保存</el-button>
          </div>
        </div>
        <!--        end right-content-->
      </div>
      <!--    end drawer-content-->
    </el-drawer>
  </div>
</template>

<script setup>
import { computed, getCurrentInstance, ref } from "vue";
import { Plus, CopyDocument } from "@element-plus/icons-vue";
import { cloneDeep } from "lodash";
import { VueDraggableNext } from "vue-draggable-next";
import ListSetting from "./components/ListSetting.vue";
import GroupRules from "./components/GroupRules";
import * as requestApi from "@/apis/groups";
import { groupTabs } from "./config";
import { parseOrDefault } from "@/utils";

const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["update:modelValue", "workApplySave", "checkSetGroup"]);
const showGroupManage = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

// 是否刷新数据
const isRefresh = ref(false);

/**
 * 分组列表
 */
const isLoadingGroupList = ref(false);
const groupList = ref([]);
const filterGroupList = ref([]);
const currentClickIndex = ref(-1);
const getGroupList = async () => {
  try {
    isLoadingGroupList.value = true;
    const { data } = await requestApi.groupList();
    groupList.value = data ?? [];
    filterGroupList.value = groupList.value?.slice(1) ?? [];
    isLoadingGroupList.value = false;
  } catch (err) {
    isLoadingGroupList.value = false;
    console.log(err);
  }
};

/**
 * 新增分组
 */
const handelAddGroup = () => {
  const isHasUnfinished = groupList.value?.filter(i => !i.groupName || i.isEdit);
  if (isHasUnfinished?.length) {
    return proxy.$modal.msgError("请先完成填写后再进行新增操作");
  }
  groupList.value.unshift({ isEdit: true, groupName: "" });
  groupId.value = "";
  currentClickIndex.value = groupList.value.length - 1;
};
/**
 * 编辑分组
 * @param item
 */
const handelEditGroup = item => {
  const isHasUnfinished = groupList.value?.filter(i => !i.groupName || i.isEdit);
  if (isHasUnfinished?.length) {
    return proxy.$modal.msgError("请先完成填写后再进行新增操作");
  }
  currentClickIndex.value = -1;
  item.isEdit = true;
  item.editTitle = item.groupName;
};
/**
 * 提交分组
 * @param item
 */
const saveGroup = async item => {
  if (!item.groupName) {
    return proxy.$modal.msgError("分组名称不能为空");
  }
  try {
    isLoadingGroupList.value = true;
    const params = {
      groupName: item.groupName
    };
    item.groupId ? await requestApi.updateGroup(item.groupId, params) : await requestApi.addGroup(params);
    isRefresh.value = true;
    proxy.$modal.msgSuccess("保存成功");
    isLoadingGroupList.value = false;
    getGroupList();
  } catch (err) {
    isLoadingGroupList.value = false;
  }
};
/**
 * 删除分组
 * @param item
 * @param index
 */
const handelDeleteGroup = (item, index) => {
  proxy.$modal.confirm("请确定是否删除分组？").then(async () => {
    try {
      if (!item.groupId) {
        groupList.value.splice(index, 1);
        return;
      }
      isLoadingGroupList.value = true;
      await requestApi.delGroup(item.groupId);
      groupList.value.splice(index, 1);
      isRefresh.value = true;
      proxy.$modal.msgSuccess("删除成功");
      groupId.value = "";
      isLoadingGroupList.value = false;
    } catch (err) {
      isLoadingGroupList.value = false;
      proxy.$modal.mesgError("删除失败");
    }
  });
};

/**
 * 分组拖动排序
 */
const deepCloneGroupList = ref([]);
const handleTypeDragStart = () => {
  deepCloneGroupList.value = cloneDeep(groupList.value);
};
const handleTypeDragEnd = async () => {
  try {
    const ids = groupList.value?.map(item => item.groupId) || [];
    await requestApi.sortGroup(ids);
    isRefresh.value = true;
    proxy.$modal.msgSuccess("操作成功");
    currentClickIndex.value = -1;
  } catch (err) {
    proxy.$modal.msgError("操作失败");
    groupList.value = cloneDeep(deepCloneGroupList.value);
  }
};

/**
 * 复制分组
 */
const copyGroup = item => {
  if (!groupId.value) return proxy.$modal.msgError("请先选择分组");
  proxy.$modal
    .confirm(`确定复制【${item.groupName}】分组吗？`)
    .then(() => {
      getGroupDetail(item.groupId);
      proxy.$modal.msgSuccess("复制成功");
    })
    .catch(err => {});
};

/**
 * 分组详情
 */
const isLoadingGroupDetail = ref(false);
// tabs
const currentTabIndex = ref(0);
// 分组id
const groupId = ref("");
const groupListConfig = ref([]);
const groupRulesConfig = ref({});
const getGroupDetail = async groupId => {
  try {
    isLoadingGroupDetail.value = true;
    const { data } = await requestApi.groupDetail(groupId);
    groupRulesConfig.value = parseOrDefault(data?.groupConfig, {});
    groupListConfig.value = parseOrDefault(data?.groupListConfig, []);
    isLoadingGroupDetail.value = false;
  } catch (err) {
    isLoadingGroupDetail.value = false;
    console.log(err);
  }
};
const clickGroupItem = async (item, index) => {
  if (!item.groupName) return;
  const isEditGroupList = groupList.value.filter(i => i.isEdit);
  if (isEditGroupList.length > 0) {
    return proxy.$modal.msgError("请先完成填写后再进行新增操作");
  }
  currentClickIndex.value = index;
  // 初始化Tab
  currentTabIndex.value = 0;
  groupId.value = item.groupId;
  getGroupDetail(item.groupId);
};

/**
 * 保存列表/分组设置
 */
const checkSubForm = () => {
  let isErr = false;
  groupRulesConfig.value?.conditionGroupList?.forEach(item => {
    item.conditionList.forEach(subItem => {
      if (!(subItem.id && subItem.compare && subItem.value?.length)) {
        subItem.isErr = true;
        isErr = true;
      }
    });
  });
  return isErr;
};
const handleConfirm = async () => {
  try {
    if (checkSubForm()) return proxy.$modal.msgError("分组规则所有选项均必填");
    isLoadingGroupDetail.value = true;
    const postData = {
      groupConfig: JSON.stringify(groupRulesConfig.value),
      groupListConfig: JSON.stringify(groupListConfig.value)
    };
    await requestApi.saveGroupSetting(groupId.value, postData);
    isRefresh.value = true;
    proxy.$modal.msgSuccess("保存成功");
    isLoadingGroupDetail.value = false;
    handleCancel();
  } catch (err) {
    isLoadingGroupDetail.value = false;
    console.log(err);
  }
};
const handleCancel = () => {
  groupList.value = [];
  groupId.value = "";
  groupListConfig.value = [];
  groupRulesConfig.value = {};
  showGroupManage.value = false;
  emit("checkSetGroup", isRefresh.value);
};

getGroupList();
</script>

<style scoped lang="scss">
@use "index.scss";
</style>
